<!--首页-->
<template>
  <div class="dashboard-container">
    <!-- 顶部KPI卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-production">
            <svg-icon icon-class="skill" class-name="card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">今日计划完成数</div>
            <count-to :start-val="0" :end-val="planCompletionRate" :duration="3000"  class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-coil">
            <svg-icon icon-class="form" class-name="card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">正在执行的工单数</div>
            <count-to :start-val="0" :end-val="steelCoilCount" :duration="2600" class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-quality">
            <svg-icon icon-class="bug" class-name="card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">今日质量异常数</div>
            <count-to :start-val="0" :end-val="abnormalNumber" :duration="2800" class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-oee">
             <svg-icon icon-class="chart" class-name="card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">工作中的设备</div>
            <count-to :start-val="0" :end-val="equipmentEnableCount" :duration="3200" :decimals="1" suffix="台" class="card-panel-num" />
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 左侧内容 -->
      <el-col :span="16">
        <!-- 生产订单跟踪 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>生产产品跟踪</span>
            
          </div>
          <el-table :data="productionOrderData" style="width: 100%">
            <el-table-column prop="productName" label="产品名称"></el-table-column>
            <el-table-column prop="productSfn" label="产品规格"></el-table-column>
            <el-table-column prop="plannedQty" label="计划产量(吨)"></el-table-column>
            <el-table-column prop="completedQty" label="已完成(吨)"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '进行中' ? 'primary' : 'success'">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 生产实时监控 -->
        <el-card class="box-card" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>产品产量实时监控 (最近24小时)</span>
          </div>
          <div v-if="noLineChartData" style="height: 300px; width: 100%; display: flex; justify-content: center; align-items: center; color: #666;">
            <p>还没有产品制造完成</p>
          </div>
          <div v-else ref="lineChart" style="height: 300px; width: 100%;"></div>
        </el-card>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :span="8">
        <!-- 快捷入口 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>快捷入口</span>
          </div>
          <div class="quick-access">
            <el-button type="primary" icon="el-icon-plus" @click="handleNavigate('production')">下达生产指令</el-button>
            <el-button type="success" icon="el-icon-check" @click="handleNavigate('quality')">质量检验录入</el-button>
            <el-button type="info" icon="el-icon-search" @click="handleNavigate('inventory')">库存查询</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="handleNavigate('equipment')">设备状态监控</el-button>
          </div>
        </el-card>

        <!-- 钢卷库存概览 -->
        <el-card class="box-card" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>钢卷库存概览</span>
          </div>
          <div ref="pieChart" style="height: 260px; width: 100%;"></div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import CountTo from 'vue-count-to';
import * as echarts from 'echarts';
import { selectPlanCompletionRate, selectSteelCoil, selectAbnormalNumber, selectProductionProductTracking, selectSbEquipmentEnable, LineChart, PieChart } from "@/api/qc/home";

export default {
  name: "Dashboard",
  components: {
    CountTo
  },
  data() {
    return {
      planCompletionRate: 0, // 今日计划完成率
      steelCoilCount: 0, // 当前在制钢卷数量
      abnormalNumber: 0, // 今日质量异常数
      equipmentEnableCount: 0, // 工作中的设备数
      // 生产订单跟踪数据
      productionOrderData: [],
      lineChart: null,
      pieChart: null,
      noLineChartData: false
    };
  },
  mounted() {
    this.initLineChart();
    this.initPieChart();
    this.getPlanCompletionRate();
    this.getSteelCoilCount();
    this.getAbnormalNumber();
    this.getProductionProductTracking();
    this.getSbEquipmentEnable();
  },
  beforeDestroy() {
    if (this.lineChart) {
      this.lineChart.dispose();
      this.lineChart = null;
    }
    if (this.pieChart) {
      this.pieChart.dispose();
      this.pieChart = null;
    }
  },
  methods: {
    // 获取今日计划完成率
    getPlanCompletionRate() {
      selectPlanCompletionRate().then(response => {
        if (response !== null && response !== undefined) {
          // 任何数值(包括0)都是有效值
          if (typeof response === 'number') {
            this.planCompletionRate = response;
          } else if (response && response.data !== null && response.data !== undefined) {
            this.planCompletionRate = response.data;
          } else {
            this.planCompletionRate = 0;
          }
        } else {
          this.planCompletionRate = 0;
        }
      }).catch(error => {
        console.error('获取今日计划完成率异常:', error);
        this.planCompletionRate = 0;
      });
    },
    
    // 获取当前在制钢卷数量
    getSteelCoilCount() {
      selectSteelCoil().then(response => {
        if (response !== null && response !== undefined) {
          // 任何数值(包括0)都是有效值
          if (typeof response === 'number') {
            this.steelCoilCount = response;
          } else if (response && response.data !== null && response.data !== undefined) {
            this.steelCoilCount = response.data;
          } else {
            this.steelCoilCount = 0;
          }
        } else {
          this.steelCoilCount = 0;
        }
      }).catch(error => {
        console.error('获取当前在制钢卷数量异常:', error);
        this.steelCoilCount = 0;
      });
    },
    
    // 获取今日质量异常数
    getAbnormalNumber() {
      selectAbnormalNumber().then(response => {
        if (response !== null && response !== undefined) {
          // 任何数值(包括0)都是有效值
          if (typeof response === 'number') {
            this.abnormalNumber = response;
          } else if (response && response.data !== null && response.data !== undefined) {
            this.abnormalNumber = response.data;
          } else {
            this.abnormalNumber = 0;
          }
        } else {
          this.abnormalNumber = 0;
        }
      }).catch(error => {
        console.error('获取今日质量异常数异常:', error);
        this.abnormalNumber = 0;
      });
    },
    
    // 获取生产订单跟踪数据
    getProductionProductTracking() {
      selectProductionProductTracking().then(response => {
        if (response && response.rows) {
          this.productionOrderData = response.rows;
        } else if (response && Array.isArray(response)) {
          this.productionOrderData = response;
        } else if (response && response.data && Array.isArray(response.data)) {
          this.productionOrderData = response.data;
        } else {
          this.productionOrderData = [];
          console.error('获取生产订单跟踪数据失败:', response);
        }
      }).catch(error => {
        console.error('获取生产订单跟踪数据异常:', error);
        this.productionOrderData = [];
      });
    },
    
    // 获取工作中的设备数
    getSbEquipmentEnable() {
      selectSbEquipmentEnable().then(response => {
        if (response !== null && response !== undefined) {
          // 任何数值(包括0)都是有效值
          if (typeof response === 'number') {
            this.equipmentEnableCount = response;
          } else if (response && response.data !== null && response.data !== undefined) {
            this.equipmentEnableCount = response.data;
          } else {
            this.equipmentEnableCount = 0;
          }
        } else {
          this.equipmentEnableCount = 0;
        }
      }).catch(error => {
        console.error('获取工作中的设备数异常:', error);
        this.equipmentEnableCount = 0;
      });
    },
    
    // 初始化产量折线图
    initLineChart() {
      LineChart().then(response => {
        console.log('折线图数据:', response);
        
        // 从响应中提取数据
        const lineData = response.data || response.rows || response || [];
        
        // 处理返回的生产线产量数据
        if (lineData && lineData.length > 0) {
          this.noLineChartData = false;
          this.$nextTick(() => {
            const xAxisData = lineData.map(item => item.production_line_name);
            const seriesData = lineData.map(item => item.total_completed_qty);
            
            this.lineChart = echarts.init(this.$refs.lineChart);
            this.lineChart.setOption({
              tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c} 吨'
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: {
                type: 'category',
                data: xAxisData,
                axisLabel: {
                  interval: 0,
                  rotate: 30
                }
              },
              yAxis: {
                type: 'value',
                name: '产量 (吨)'
              },
              series: [{
                name: '生产线产量',
                type: 'bar',
                data: seriesData,
                label: {
                  show: true,
                  position: 'top',
                  formatter: '{c} 吨'
                },
                itemStyle: {
                  color: '#36a3f7'
                }
              }]
            });
          });
        } else {
          // 如果数据为空或格式不匹配，显示提示信息
          this.noLineChartData = true;
        }
      }).catch(error => {
        console.error('获取折线图数据异常:', error);
        this.noLineChartData = true;
      });
    },
    
    // 初始化库存饼图
    initPieChart() {
      PieChart().then(response => {
        console.log('饼图数据:', response);
        
        // 从响应中提取数据
        const pieData = response.data || response.rows || response || [];
        
        // 处理返回的库存状态数据
        if (pieData && pieData.length > 0) {
          // 过滤掉不需要的分类，避免"在库"与"冻结/未冻结"数据重复
          const filteredData = pieData.filter(item => 
            // 仅保留以下分类，不包括"在库"，因为"在库"是"冻结"和"未冻结"的总和
            item.category === '冻结' || 
            item.category === '未冻结' || 
            item.category === '再制作中' || 
            item.category === '不合格'
          );
          
          const chartData = filteredData
            .filter(item => item.value !== null) // 过滤掉null值
            .map(item => ({
              name: item.category,
              value: parseFloat(item.value) || 0
            }));
          
          if (chartData.length > 0) {
            this.pieChart = echarts.init(this.$refs.pieChart);
            this.pieChart.setOption({
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                orient: 'vertical',
                left: 10,
                data: chartData.map(item => item.name)
              },
              series: [{
                name: '钢卷状态',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                  show: true,
                  formatter: '{b}: {c}'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '16',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: true
                },
                data: chartData
              }]
            });
            return;
          }
        }
        
        // 如果数据为空或格式不匹配，使用默认数据
        const defaultData = [
          { value: 1048, name: '合格' },
          { value: 735, name: '待检' },
          { value: 580, name: '不合格' },
          { value: 484, name: '已锁定' }
        ];
        
        this.pieChart = echarts.init(this.$refs.pieChart);
        this.pieChart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 10,
            data: defaultData.map(item => item.name)
          },
          series: [{
            name: '钢卷状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: defaultData
          }]
        });
      }).catch(error => {
        console.error('获取饼图数据异常:', error);
        // 使用默认数据
      });
    },
    
    // 快捷入口导航
    handleNavigate(target) {
      switch(target) {
        case 'production':
          this.$router.push('/sc/task');
          break;
        case 'quality':
          this.$router.push('/qc/PendingTasks');
          break;
        case 'inventory':
          this.$router.push('/ck/inventory');
          break;
        case 'equipment':
          this.$router.push('/sb/equipment-ledger');
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.panel-group {
  margin-bottom: 20px;

  .card-panel-col {
    margin-bottom: 20px;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }
      .icon-production {
        background: #36a3f7;
      }
      .icon-coil {
        background: #40c9c6;
      }
      .icon-quality {
        background: #f4516c;
      }
      .icon-oee {
        background: #f4b980;
      }
    }

    .icon-production {
      color: #36a3f7;
    }
    .icon-coil {
      color: #40c9c6;
    }
    .icon-quality {
      color: #f4516c;
    }
    .icon-oee {
      color: #f4b980;
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

.box-card {
  width: 100%;
}

.quick-access {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  
  .el-button {
    width: 100%;
    margin-left: 0;
    margin-bottom: 10px;
  }
}
</style> 